﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Common.Model;
using Common.PddApi;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Operation;
using pinduoduo.CefHandler;
using pinduoduo.Model;
using pinduoduo.Model.New;
using pinduoduo.Service;
using pinduoduo.Util;
using RestSharp;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo
{

    public partial class MainWindows : Form
    {

        public ChromiumWebBrowser chromeBrowser;
        private ChromiumWebBrowser JsBrowser;

        public RequestContext context;
        private IList<PddToken> pddTokens = new List<PddToken>();
        private PddTokenService pddTokenService = new PddTokenService();
        private Dictionary<double, string> kvDictonary = new Dictionary<double, string>();
        private BindingSource bs = new BindingSource();
        private List<ListItem> items = new List<ListItem>();
        private IEnumerable<PddAddressDBModel> pddAddressDBModelList = new List<PddAddressDBModel>();
        //标准地理位置
        private IEnumerable<AreaModel> areaModelList = new List<AreaModel>();
        private List<string> gIdList = new List<string>();
        private string activityID;

        private string pddurl = "http://yangkeduo.com/";

        private ChromiumWebBrowser AccountChromeBrowser;
        private RequestContext AccountContext;
        private PddToken AccountPddToken;
        private double CurServerTime = SystemUtil.GetTimeStamp();

        public MainWindows()
        {
            InitializeComponent();
            MonitorExpirTask();
        }

        private async void MonitorExpirTask()
        {
            string curTimeStr = await G_Api.GetServerTime();
            if (string.IsNullOrWhiteSpace(curTimeStr))
            {
                MessageBox.Show("与服务器连接失败");
                return;
            }
            DateTime expireDate = (DateTime)G_Api.Cur_VipUser.expireDate;
            var expireTime = SystemUtil.GetTimeStamp(expireDate);
            CurServerTime = double.Parse(curTimeStr);
            await Task.Run(() =>
            {
                while (true)
                {
                    CurServerTime += 1000;
                    if (expireTime < CurServerTime)
                    {
                        MessageBox.Show("您的软件到期，请充值！");
                        this.BeginInvoke(new Action(() =>
                        {
                            this.Close();
                        }));

                        System.Environment.Exit(0);
                        break;
                    }
                    Thread.Sleep(1000);
                }
            });
        }

        private async void MonitorExpirTask2()
        {
            await Task.Run(async () =>
            {
                while (true)
                {
                    var softwareExpire = await G_Api.SoftwareExpire();

                    if (!softwareExpire)
                    {
#if !DEBUG
                        this.BeginInvoke(new Action(() =>
                        {
                            this.Close();
                        }));
                        System.Environment.Exit(0);
                        break;
#endif
                    }
                    AutoUpdate.GetInstance().updater.BeginCheckUpdateInProcess();
                    Thread.Sleep(1000 * 60 * 10);
                }
            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MonitorExpirTask2();
            this.expireData.Text = "到期时间：" + G_Api.Cur_VipUser.expireDate;
            var settings = new CefSettings
            {
                Locale = "zh-CN"
            };
            // settings.UserAgent = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Mobile Safari/537.36 Edg/89.0.774.54";
            settings.RootCachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\";
            //settings.CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\";
            settings.PersistSessionCookies = true;
            settings.PersistUserPreferences = true;

            Cef.Initialize(settings);

            InitializeChromium();
            var tokens = pddTokenService.GetAllToken();


            pddAddressDBModelList = DataBaseHelper.SqLiteDBCon.GetAll<PddAddressDBModel>();
            areaModelList = DataBaseHelper.SqLiteDBCon.GetAll<AreaModel>();
            var pddGoods = DataBaseHelper.SqLiteDBCon.GetAll<PddGood>();
            this.dataGridView1.AutoGenerateColumns = false;

            this.dataGridView1.AutoSize = false;
            this.dataGridView1.DataSource = null;
            pddTokens = pddTokens.Concat(tokens).ToList();
            ;
            this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
            SetProxy(chromeBrowser, "");

            comboBox1.DisplayMember = "Text";
            comboBox1.ValueMember = "Value";
            comboBox1.DataSource = items;
            AutoSizeColumn(dataGridView1);

            foreach (var item in pddGoods)
            {
                this.goods_id.Items.Add(item.good_id);
            }

            this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dataGridView1_RowPostPaint);

            InitializeAccountChromium();

            PddToken pddToken = pddTokenService.GetAllToken().Where(x => x.account_type == 1).FirstOrDefault();

            AccountPddToken = pddToken;

            sku = new BrowserFrom();
        }


        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                dataGridView1.RowHeadersWidth - 4,
                e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dataGridView1.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }


        //初始化浏览器并启动
        public void InitializeChromium()
        {
            chromeBrowser = new ChromiumWebBrowser("http://yangkeduo.com/");
            //chromeBrowser = new ChromiumWebBrowser("https://mapi.alipay.com/gateway.do?service=alipay.wap.create.direct.pay.by.user&partner=2088911201740274&seller_id=pddzhifubao%40yiran.com&payment_type=1&notify_url=https%3A%2F%2Fpaynotify.pinduoduo.com%2Fnotify%2F9&out_trade_no=XP1221042213201415252602007651&subject=%E5%95%86%E6%88%B7%E5%8D%95%E5%8F%B7XP1221042213201415252602007651&total_fee=14.06&return_url=http%3A%2F%2Fmobile.yangkeduo.com%2Ftransac_wappay_callback.html%3Forder_sn%3D210422-059142308830476%26prepay_type%3D&sign=MLRnurVjbKlQc1iNhuG9kmug97lCQJMFSelCiNL2v3FNeZAorACTEuhs3979weP%2FuT5IjPSeBiw3fIxucr70MLOCwyT7B7xap57mgKgEONiwN9O1kQk%2FDE3MUlNJGg6cuFDrd2fkmcn6W%2F8Y49iI9HywEHYOB2aPEaK6weZH7Bs%3D&sign_type=RSA&goods_type=1&_input_charset=utf-8&it_b_pay=2021-04-23%2013%3A57");

            context = new RequestContext(new RequestContextSettings()
            {
                CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\global1\\",
                PersistSessionCookies = true,
                PersistUserPreferences = true,
            });

            chromeBrowser.RequestContext = context;

            chromeBrowser.KeyboardHandler = new CEFKeyBoardHander();
            chromeBrowser.FrameLoadEnd += Browser_FrameLoadEnd;

            this.panel1.Controls.Add(chromeBrowser);

            chromeBrowser.Dock = DockStyle.Fill;
        }

        private async void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定退出登录吗", "提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                bool reslut = await context.GetCookieManager(null).FlushStoreAsync();
                sku.myRequestHandler.Dispose();
                Cef.Shutdown();
                System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(this.goods_id.Text);
            if (pdd != null)
            {
                SetGoodInfo(pdd);
                this.source.Text = pdd.SourceKeywords;
            }

        }

        private void SetGoodInfo(PddGood pdd)
        {
            if (pdd == null)
            {
                MessageBox.Show("请先本地获取！");
                return;
            }

            if (pdd.type == (int)PddGoodSource.DuoDuo)
            {

                dynamic arrdata = JArray.Parse(pdd.sku);

                this.items.Clear();
                gIdList.Clear();
                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                activityID = pdd.atvid;
                foreach (dynamic item in arrdata)
                {
                    double skuId = item.skuID;
                    string normalPriceStr = item.normalPrice;
                    string groupPriceStr = item.groupPrice;
                    dynamic specs = item.specs;
                    //    double goodsId = item.goodsId;
                    string spec_value = "";
                    foreach (dynamic spec in specs)
                    {
                        spec_value = spec.spec_value;
                    }

                    try
                    {
                        //string groupPrice = Math.Round((decimal)(Convert.ToDouble(groupPriceStr) / Convert.ToDouble(100)), 2).ToString() + " 元";
                        //string normalPrice = Math.Round((decimal)(Convert.ToDouble(normalPriceStr) / Convert.ToDouble(100)), 2).ToString() + " 元";
                        string text = "拼单:" + groupPriceStr + " 元" + "批发:" + normalPriceStr + "元 " + spec_value;
                        items.Add(new ListItem(skuId, text));
                    }
                    catch { }

                }
            }

            if (pdd.type == (int)PddGoodSource.Pifa)
            {

                dynamic arrdata = JArray.Parse(pdd.sku);
                this.items.Clear();
                gIdList.Clear();
                activityID = pdd.atvid;

                foreach (dynamic item in arrdata)
                {
                    double skuId = item.skuId;
                    string normalPriceStr = item.wholesalePrice;
                    string groupPriceStr = item.groupPrice;
                    dynamic specs = item.skuSpecs;
                    //double goodsId = item.goodsId;
                    string spec_value = "";
                    foreach (dynamic spec in specs)
                    {
                        spec_value = spec.specValue;
                    }

                    try
                    {
                        string groupPrice = Math.Round((decimal)(Convert.ToDouble(groupPriceStr) / Convert.ToDouble(100)), 2).ToString() + " 元";
                        string normalPrice = Math.Round((decimal)(Convert.ToDouble(normalPriceStr) / Convert.ToDouble(100)), 2).ToString() + " 元";
                        string text = "拼单:" + groupPrice + " 元" + "批发:" + normalPrice + "元 " + spec_value;
                        items.Add(new ListItem(skuId, text));
                    }
                    catch { }


                }

            }
            //从页面抓取的
            if (pdd.type == 0)
            {
                string sku = pdd.sku;
                //var arrdata = Newtonsoft.Json.Linq.JArray.Parse(sku);
                var skuObj = JsonHelper.DeserializeObject<List<PddPageGood>>(sku);

                this.items.Clear();
                gIdList.Clear();
                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                activityID = pdd.atvid;
                foreach (dynamic item in skuObj)
                {
                    double skuId = item.skuId;
                    string normalPrice = item.normalPrice;
                    string groupPrice = item.groupPrice;
                    dynamic specs = item.specs;
                    double goodsId = item.goodsId;

                    string spec_value = "";
                    foreach (dynamic spec in specs)
                    {
                        spec_value = spec.spec_value;
                    }
                    string text = "拼单:" + groupPrice + " 元" + "单买:" + normalPrice + "元 " + spec_value;
                    items.Add(new ListItem(skuId, text));
                }
            }

            // 通过渲染界面 接口拿的数据
            if (pdd.type == (int)PddGoodSource.PuTong)
            {
                string sku = pdd.sku;

                dynamic arrdata = JArray.Parse(pdd.sku);

                this.items.Clear();
                gIdList.Clear();
                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                activityID = pdd.atvid;
                foreach (dynamic item in arrdata)
                {
                    double skuId = item.sku_id;
                    string normalPrice = item.normal_price;
                    string groupPrice = item.group_price;
                    dynamic specs = item.specs;
                    double goodsId = item.goods_id;

                    string spec_value = "";
                    foreach (dynamic spec in specs)
                    {
                        spec_value = spec.spec_value;
                    }
                    string text = "拼单:" + groupPrice.Insert(groupPrice.Length - 2, ".") + " 元" + "单买:" + normalPrice.Insert(normalPrice.Length - 2, ".") + "元 " + spec_value;
                    items.Add(new ListItem(skuId, text));
                }
            }

            this.comboBox1.BeginInvoke(new Action(() =>
            {
                comboBox1.DataSource = null;
                comboBox1.DisplayMember = "Text";        //显示
                comboBox1.ValueMember = "Value";        //值
                comboBox1.DataSource = items;
                if (items.Count() > 0)
                {
                    comboBox1.SelectedIndex = 0;
                }
            }));
        }

        /// <summary> 
        /// 获取时间戳 -秒
        /// </summary> 
        /// <returns></returns> 
        public static int GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt32(ts.TotalSeconds);
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            if (AccountPddToken == null)
            {
                MessageBox.Show("请先登陆主账号");
                return;
            }

            if (this.pifaRadioButton.Checked)
            {
                string url = "https://pifa.pinduoduo.com/goods/detail/?gid=" + this.goods_id.Text.Trim();

                if (!sku.Visible)
                {
                    sku.action = UpdateGoodInfo;
                    sku.Show();
                    sku.LoadUrl(url, 5000);
                }
                return;
            }
            if (this.duoduoRadioButton.Checked)
            {
                if (this.goods_id.Text.StartsWith("https://p.pinduoduo.com/"))
                {
                    string url = this.goods_id.Text;

                    if (!sku.Visible)
                    {
                        sku.action = UpdateGoodInfo;
                        sku.SetGoodIdAction = SetGoodId;
                        sku.Show();
                        sku.LoadUrl(url, 5000, (int)PddGoodSource.DuoDuo);
                    }
                    return;
                }
                else
                {
                    MessageBox.Show("请输入多多链接");
                    return;
                }
            }

            var response = await PddApi.GetGoodInfo(this.goods_id.Text.Trim(), AccountPddToken);

            if (string.IsNullOrWhiteSpace(response.Content))
            {
                MessageBox.Show("获取数据为空！接口有问题啦");
                return;
            }

            if (response.Content.Contains("请登录后再操作"))
            {
                MessageBox.Show("请登录后再操作");
                return;
            }

            if (response.Content.Contains("verify_auth_token")
               && response.Content.Contains("error_code"))
            {
                MessageBox.Show("请去主账号里输入验证码");
                return;
            }

            if (response.Content.Contains("verify_auth_token")
              && response.Content.Contains("error_code"))
            {
                MessageBox.Show("请输入验证码");
                return;
            }

            if (response.StatusCode != HttpStatusCode.OK)
            {
                MessageBox.Show("获取失败，请检查主号是否有异常");
                return;
            }

            PddGood pddGood = PddApi.PaserGoogInfo(response, this.goods_id.Text.Trim());

            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(this.goods_id.Text.Trim());

            SetGoodInfo(pdd);
            this.source.Text = pdd.SourceKeywords;

            //if (string.IsNullOrWhiteSpace(this.goods_id.Text))
            //{
            //    return;
            //}
            //PddToken pddToken = this.dataGridView1.CurrentRow.DataBoundItem as PddToken;

            //if (pddToken == null)
            //{
            //    return;
            //}
            //PddSkuFrom pddSkuFrom =  new PddSkuFrom(this.goods_id.Text);
            //pddSkuFrom.Show();
        }

        private void SetGoodId(string goodId)
        {
            this.goods_id.Text = goodId;
        }

        private void UpdateGoodInfo()
        {
            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(this.goods_id.Text.Trim());
            if (pdd != null)
            {
                SetGoodInfo(pdd);
                this.source.Text = pdd.SourceKeywords;
            }
        }

        /// <summary>
        /// 页面加载结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            //string url = "https://mclient.alipay.com/h5/loginIdPwdToLogin.htm";

            //检测账号是否过期
            //if (e.Url.Contains("http://mobile.yangkeduo.com/login.html?"))
            //{
            //    List<CefSharp.Cookie> cookies = await context.GetCookieManager(null).VisitAllCookiesAsync();
            //    if (cookies == null || cookies.Count == 0)
            //    {
            //        this.dataGridView1.CurrentRow.Cells["TokenStatus"].Value = "过期";
            //        return;
            //        //MessageBox.Show("请先登录账号");
            //    }

            //    CefSharp.Cookie PDDAccessTokenCookie = cookies.Where(x => { return x.Name == "PDDAccessToken"; }).FirstOrDefault();
            //    CefSharp.Cookie pdd_user_id_cookie = cookies.Where(x => { return x.Name == "pdd_user_id"; }).FirstOrDefault();
            //    if (PDDAccessTokenCookie != null || pdd_user_id_cookie != null)
            //    {
            //        this.dataGridView1.CurrentRow.Cells["TokenStatus"].Value = "过期";
            //        //MessageBox.Show("请先登录账号");
            //        //return;
            //    }

            //    //return;
            //}

            if (!e.Url.Contains("http://yangkeduo.com/goods.html?goods_id="))
            {
                return;
            }

            var task02 = e.Frame.GetSourceAsync();
            await task02.ContinueWith(t =>
             {
                 if (!t.IsFaulted)
                 {
                     string resultStr = t.Result;
                 }
             });

            string script = @"(function() { return  window.rawData.store.initDataObj.goods;})()";

            await chromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
             {
                 var response = x.Result;

                 if (response.Success && response.Result != null)
                 {
                     dynamic obj = response.Result;
                     dynamic skuObj = obj.skus;
                     this.kvDictonary.Clear();
                     this.items.Clear();
                     activityID = "";
                     gIdList.Clear();
                     foreach (dynamic item in skuObj)
                     {
                         double skuId = item.skuId;
                         string normalPrice = item.normalPrice;
                         string groupPrice = item.groupPrice;
                         dynamic specs = item.specs;
                         double goodsId = item.goodsId;

                         string spec_value = "";
                         foreach (dynamic spec in specs)
                         {
                             spec_value = spec.spec_value;
                         }
                         string text = "拼单:" + groupPrice + " 元" + "单买:" + normalPrice + "元 " + spec_value;

                         kvDictonary.Add(skuId, text);
                         items.Add(new ListItem(skuId, text));
                     }

                     //obj.groupTypes

                     this.comboBox1.BeginInvoke(new Action(() =>
                      {
                          comboBox1.DataSource = null;
                          comboBox1.DisplayMember = "Text";        //显示
                          comboBox1.ValueMember = "Value";        //值
                          comboBox1.DataSource = items;
                          if (items.Count() > 0)
                          {
                              comboBox1.SelectedIndex = 0;
                          }
                      }));

                 }
             });

        }

        private void button1_Click(object sender, EventArgs e)
        {
            chromeBrowser.Back();
        }

        private async void pifa(PddGood pdd, PddToken pddToken, CreateOrderItemListItem createOrderItemListItem, string addressId, string daili)
        {
            string urlAnti = "https://mms.pinduoduo.com/pifa/goods/singleBuy";
            string ant = FackUtil.GetAnti(chromeBrowser, urlAnti);

            if (string.IsNullOrWhiteSpace(ant))
            {
                MessageBox.Show("下单签名失败，请在中间切换个网友试试看行不");
                return;
            }

            var res = await PddPiFaApi.SingleBuy(pddToken, createOrderItemListItem, ant, daili);
            if (res.StatusCode != HttpStatusCode.OK)
            {
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                MessageBox.Show("下单失败");
                return;
            }

            var jo = JObject.Parse(res.Content);

            var success = jo["success"].ToString();
            var errorCode = jo["errorCode"].ToString();
            var errorMsg = jo["errorMsg"].ToString();
            if (success.ToLower() != "true")
            {
                if (errorCode == "6000005")
                {
                    MessageBox.Show(errorMsg);
                    return;
                }
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                MessageBox.Show("下单失败");
                return;
            }

            var qrKey = jo["result"]["qrKey"].ToString();

            if (string.IsNullOrWhiteSpace(qrKey))
            {
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                MessageBox.Show("下单失败");
                return;
            }
            var curl = jo["result"]["curl"].ToString();

            string html = await PddPiFaApi.GetTransacOrderCouponHtml(pddToken, curl, daili);
            var pifaClientOrderCreate = PaserOrderHtml(html);
            if (pifaClientOrderCreate == null)
            {
                return;
            }
            urlAnti = "https://mobile.yangkeduo.com/proxy/api/api/pifa-client/order/order_create";
            ant = FackUtil.GetAnti(chromeBrowser, urlAnti);

            pifaClientOrderCreate.secret_key = qrKey;
            pifaClientOrderCreate.anti_content = ant;
            pifaClientOrderCreate.page_id = "";
            pifaClientOrderCreate.address_id = double.Parse(addressId);
            res = await PddPiFaApi.PiFaOrderCreate(pddToken, pifaClientOrderCreate, daili);
            if (res.StatusCode != HttpStatusCode.OK)
            {
                MessageBox.Show("下单失败！");
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
            }

            jo = JObject.Parse(res.Content);

            success = jo["success"].ToString();

            if (success.ToLower() != "true")
            {
                MessageBox.Show("下单失败！");
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                return;
            }
            var order_sns = jo["result"]["order_sns"].FirstOrDefault()?.ToString();
            var parent_order_sn = jo["result"]["parent_order_sn"].ToString();

            res = await PddPiFaApi.PiFPrepay(pddToken, parent_order_sn, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                MessageBox.Show("下单失败！");
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                return;
            }
            jo = JObject.Parse(res.Content);
            var query = jo["query"];
            var total_fee = jo["query"]["total_fee"].ToString();

            var gateway_url = jo["gateway_url"];

            StringBuilder stringBuilder = new StringBuilder();
            foreach (JToken grandChild in query)
            {
                var p = grandChild as JProperty;
                string s = p.Name + ":" + p.Value;
                stringBuilder.Append(p.Name);
                stringBuilder.Append("=");
                stringBuilder.Append(Uri.EscapeDataString(p.Value.ToString()));
                stringBuilder.Append("&");
            }
            stringBuilder.Remove(stringBuilder.Length - 1, 1);
            string url = gateway_url + "?" + stringBuilder.ToString();

            Order order = new Order();
            order.goodsId = createOrderItemListItem.goodsId.ToString();
            order.orderSn = order_sns;
            order.parent_order_sn = parent_order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = createOrderItemListItem.skuNum.ToString();
            order.order_type = "批发订单";
            //order.token = pddToken.PDDAccessToken;
            order.pay_url = url;
            //order.orderState = "待支付";

            order.goodsMoney = double.Parse(total_fee) * 100 + "";
            try
            {
                this.goodsMoney.Text = total_fee + " 元";
            }
            catch
            {
            }

            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);

            chromeBrowser.Load(url);
        }

        private async Task<bool> PuTongOrder(PddToken pddToken, PDDOrder pddOrder, string daili)
        {
            var OrderResponse = await PddApi.PddOrder(pddToken.pdd_user_id, pddToken.PDDAccessToken, pddOrder, this.source.Text, daili);

            if (OrderResponse.StatusCode == HttpStatusCode.Forbidden)
            {
                LogHelper.Logger.Error("下单失败:" + OrderResponse.Content);
                MessageBox.Show("下单失败,请重新获取商品数据试试！");
                return false;

            }

            if (string.IsNullOrWhiteSpace(OrderResponse.Content))
            {
                LogHelper.Logger.Error("下单失败");
                MessageBox.Show("下单失败,请重新获取商品数据试试！");
                return false;
            }
            PDDOrderResponse pDDOrderResponse = null;
            try
            {
                pDDOrderResponse = JsonConvert.DeserializeObject<PDDOrderResponse>(OrderResponse.Content);
            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,返回数据解析失败" + OrderResponse.Content, e1);
                MessageBox.Show("下单失败,返回数据解析失败");
                return false;
            }

            this.dataGridView1.CurrentRow.Cells["order"].Value = pDDOrderResponse.order_sn;

            pddToken.last_order_sn = pDDOrderResponse.order_sn;
            pddTokenService.UpdateToken(pddToken, true);

            PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
            pDDOrderPrepay.pay_app_id = 9;
            pDDOrderPrepay.version = 3;
            pDDOrderPrepay.order_sn = pDDOrderResponse.order_sn;
            pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + pDDOrderResponse.order_sn + "&prepay_type=";
            pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

            var res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                MessageBox.Show("下单失败,订单预付失败");
                return false;
            }

            //订单预付
            PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
            try
            {
                pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                MessageBox.Show("下单失败,订单预付失败");
                return false;
            }

            string query = GetUriParam(pDDOrderPrepayResponse.query);
            string ur1 = pDDOrderPrepayResponse.gateway_url + "?" + query;

            Order order = new Order();
            order.goodsId = pddOrder.goods.FirstOrDefault().goods_id;
            order.orderSn = pDDOrderResponse.order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = pddOrder.goods.FirstOrDefault().sku_number.ToString();
            order.pay_url = ur1;
            order.order_type = "普通订单";
            order.goodsMoney = pDDOrderResponse.order_amount.ToString();
            try
            {
                this.goodsMoney.Text = Math.Round((decimal)(Convert.ToDouble(pDDOrderResponse.order_amount) / Convert.ToDouble(100)), 2).ToString() + " 元";
            }
            catch { }


            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);

            chromeBrowser.Load(ur1);

            await PddApi.DelAddressById(pddToken, pddOrder.address_id, daili);
            return true;
        }

        private async Task<bool> DuoDuoOrder(PddGood pddGood, PddToken pddToken, PDDOrder pddOrder, string daili)
        {
          
            DuoDuoOrder duoDuoOrder = new DuoDuoOrder();
            duoDuoOrder.group_id = pddOrder.group_id;
           
            duoDuoOrder.goods = new List<GoodsItem>();
            duoDuoOrder.goods.Add(new GoodsItem(pddOrder.goods.FirstOrDefault()));
            duoDuoOrder.address_id = double.Parse(pddOrder.address_id);
  
            DuoDuoAttribute_fields duoDuoAttribute_Fields = new DuoDuoAttribute_fields();
            duoDuoAttribute_Fields.cps_sign = pddGood.cps_sign;
            duoDuoAttribute_Fields.DUO_DUO_PID = pddGood.duo_duo_pid;
            duoDuoOrder.attribute_fields = duoDuoAttribute_Fields;

            var OrderResponse = await PddApi.PddOrderDuoDuo(pddToken, duoDuoOrder,daili);

            if (OrderResponse.StatusCode == HttpStatusCode.Forbidden)
            {
                LogHelper.Logger.Error("下单失败:" + OrderResponse.Content);
                MessageBox.Show("下单失败,请重新获取商品数据试试！");
                return false;

            }

            if (string.IsNullOrWhiteSpace(OrderResponse.Content))
            {
                LogHelper.Logger.Error("下单失败");
                MessageBox.Show("下单失败,请重新获取商品数据试试！");
                return false;
            }
            PDDOrderResponse pDDOrderResponse = null;
            try
            {
                pDDOrderResponse = JsonConvert.DeserializeObject<PDDOrderResponse>(OrderResponse.Content);
            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,返回数据解析失败" + OrderResponse.Content, e1);
                MessageBox.Show("下单失败,返回数据解析失败");
                return false;
            }

            this.dataGridView1.CurrentRow.Cells["order"].Value = pDDOrderResponse.order_sn;

            pddToken.last_order_sn = pDDOrderResponse.order_sn;
            pddTokenService.UpdateToken(pddToken, true);

            PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
            pDDOrderPrepay.pay_app_id = 9;
            pDDOrderPrepay.version = 3;
            pDDOrderPrepay.order_sn = pDDOrderResponse.order_sn;
            pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + pDDOrderResponse.order_sn + "&prepay_type=";
            pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

            var res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                MessageBox.Show("下单失败,订单预付失败");
                return false;
            }

            //订单预付
            PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
            try
            {
                pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                MessageBox.Show("下单失败,订单预付失败");
                return false;
            }

            string query = GetUriParam(pDDOrderPrepayResponse.query);
            string ur1 = pDDOrderPrepayResponse.gateway_url + "?" + query;

            Order order = new Order();
            order.goodsId = pddOrder.goods.FirstOrDefault().goods_id;
            order.orderSn = pDDOrderResponse.order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = pddOrder.goods.FirstOrDefault().sku_number.ToString();
            order.pay_url = ur1;
            order.order_type = "多多订单";
            order.goodsMoney = pDDOrderResponse.order_amount.ToString();
            try
            {
                this.goodsMoney.Text = Math.Round((decimal)(Convert.ToDouble(pDDOrderResponse.order_amount) / Convert.ToDouble(100)), 2).ToString() + " 元";
            }
            catch { }


            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);

            chromeBrowser.Load(ur1);

            await PddApi.DelAddressById(pddToken, pddOrder.address_id, daili);
            return true;
        }

        private PifaClientOrderCreate PaserOrderHtml(string html)
        {
            Regex reg = new Regex("window.rawData= (?<key2>.*?)};");
            Match match = reg.Match(html);
            string tempStr = match.Groups["key2"].Value;
            if (string.IsNullOrWhiteSpace(tempStr))
            {
                MessageBox.Show("解析数据失败");
                return null;
            }
            PifaClientOrderCreate pifaClientOrderCreate = new PifaClientOrderCreate();
            pifaClientOrderCreate.sku_vos = new List<Sku_vosItem>();
            Sku_vosItem sku_VosItem = new Sku_vosItem();
            var jo = JObject.Parse(tempStr + " }");
            var goodsListStore = jo["store"]["goodsListStore"]["goodsList"].ToArray();
            var frontEnv = jo["store"]["envStore"]["frontEnv"].ToObject<int>();
            //var addressId = jo["store"]["addressInfoStore"]["addressId"].ToObject<double>();

            var goods = goodsListStore.FirstOrDefault();
            string goods_id = goods["goodsId"].ToString();
            string group_id = goods["groupId"].ToString();
            string sku_id = goods["skuId"].ToString();
            string sku_number = goods["skuNumber"].ToString();

            sku_VosItem.goods_id = double.Parse(goods_id);
            sku_VosItem.group_id = double.Parse(group_id);
            sku_VosItem.sku_id = double.Parse(sku_id);
            sku_VosItem.sku_number = int.Parse(sku_number);
            pifaClientOrderCreate.front_env = frontEnv;
            pifaClientOrderCreate.sku_vos.Add(sku_VosItem);

            return pifaClientOrderCreate;
        }
      
        /// <summary>
        /// 购买商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button4_Click(object sender, EventArgs e)
        {
            if (this.liveRadioButton.Checked)
            {
                MessageBox.Show("直播下单功能即将上线");
                return;
            }

            string imageBase64 = null;
            PddGood pddGood = DataBaseHelper.SqLiteDBCon.Get<PddGood>(this.goods_id.Text);
            if (pddGood == null)
            {
                MessageBox.Show("请先获取商品信息");
                return;
            }

            if (pddGood.SourceKeywords != this.source.Text)
            {
                pddGood.SourceKeywords = this.source.Text;
                await DataBaseHelper.SqLiteDBCon.UpdateAsync<PddGood>(pddGood);
            }
            double skuIdStr = (double)this.comboBox1.SelectedValue;
            double goodsId = double.Parse(this.goods_id.Text);

            PddToken pddToken = this.dataGridView1.CurrentRow.DataBoundItem as PddToken;
            if (pddToken == null)
            {
                MessageBox.Show("请先选择一个小号");
                return;
            }

            if (this.pifaRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.Pifa)
                {
                    MessageBox.Show("请先获取批发商品信息");
                    return;
                }
                if (pddGood.firstLadderStartValue == 0)
                {
                    MessageBox.Show("请重新获取商品信息");
                    return;
                }
                if (this.uiIntegerUpDown_sku_number.Value < pddGood.firstLadderStartValue)
                {
                    MessageBox.Show(pddGood.firstLadderStartValue + "件起购");
                    return;
                }
            }

            if (this.duoduoRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.DuoDuo)
                {
                    MessageBox.Show("请先获取多多商品信息");
                    return;
                }
            }

            if (this.puTongRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.PuTong)
                {
                    MessageBox.Show("请先获取普通商品信息");
                    return;
                }
            }

            string url1 = "http://mobile.yangkeduo.com/personal_profile.html";
            chromeBrowser.Load(url1);

            if (this.NickNameCheck.Checked)
            {
                imageBase64 = ImageUtil.GetRandomBase64Avatar(AppDomain.CurrentDomain.BaseDirectory + "avatar");

                if (string.IsNullOrWhiteSpace(imageBase64))
                {
                    MessageBox.Show("头像上传失败,原因：获取本地图片失败");
                    return;
                }
            }

            string errorMsg = string.Empty;
            string daili = G_Api.GetProxyIp(out errorMsg);

            if (string.IsNullOrEmpty(daili))
            {
                MessageBox.Show("获取代理地址失败");
                return;
            }

            this.CurIP.Text = daili;


            if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
            {
                var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken, daili);

                if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    pddToken.status = "正常";
                }
                else if (pddUserInfo.Content.Contains("error_code"))
                {
                    pddToken.status = "过期";
                }
                else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    pddToken.status = "未知";
                }
            }
            else
            {
                pddToken.status = "未知";
            }


            if (pddToken.status == "过期" || pddToken.status == "未知")
            {
                MessageBox.Show("获取用户信息异常，小号可能过期了");
                return;
            }

            if (this.favorite_like_check.Checked)
            {
                await PddApi.FavoriteGood(pddToken, this.goods_id.Text);
            }

            if (this.NickNameCheck.Checked)
            {
                bool result = await PddApi.UpdateNickName(pddToken, RandomName.GetNickName(), daili);
                if (!result)
                {
                    MessageBox.Show("修改昵称失败");
                    return;
                }

                var signature = await PddApi.Signature(pddToken, daili);
                if (string.IsNullOrWhiteSpace(signature))
                {
                    MessageBox.Show("头像上传失败,原因：获取上传签名异常");
                    return;
                }

                string imageUrl = await PddApi.UploadAvatar(pddToken, signature, imageBase64, daili);

                result = await PddApi.UpdateAvatar(pddToken, imageUrl, daili);
                if (!result)
                {
                    MessageBox.Show("头像上传失败");
                    return;
                }
            }

            string addressid = await AddAddress(this.randomAddress.Checked, pddToken, daili);
            if (string.IsNullOrWhiteSpace(addressid))
            {
                MessageBox.Show("地址设置异常");
                return;
            }


            if (this.pifaRadioButton.Checked)
            {
                CreateOrderItemListItem createOrderItemListItem = new CreateOrderItemListItem();
                createOrderItemListItem.goodsId = goodsId;
                createOrderItemListItem.skuId = skuIdStr;
                createOrderItemListItem.skuNum = this.uiIntegerUpDown_sku_number.Value;
                pifa(pddGood, pddToken, createOrderItemListItem, addressid, daili);
                return;
            }

            PDDOrder pddOrder = new PDDOrder();
            pddOrder.address_id = addressid;
            var goods = new List<Goods>();
            Goods good = new Goods();
            good.sku_id = skuIdStr.ToString();
            good.goods_id = goodsId.ToString();
            good.sku_number = this.uiIntegerUpDown_sku_number.Value;
            goods.Add(good);
            pddOrder.goods = goods;

            if (this.groupType.Text == "参团")
            {
                //pddOrder.group_id = groupID.ToString();
                pddOrder.group_id = gIdList[1];
            }
            else if (this.groupType.Text == "开团")
            {
                if (gIdList.Count == 2)
                {
                    pddOrder.group_id = gIdList[1];
                }
            }
            else if (this.groupType.Text == "单独购买")
            {
                pddOrder.group_id = gIdList.FirstOrDefault();
            }

            pddOrder.activity_id = activityID;


            //PddOrerNew pddOrerNew = new PddOrerNew();
            //pddOrerNew.source_channel = -1;
            //pddOrerNew.duoduo_type = 0;
            //pddOrerNew.activity_id = activityID;
            //pddOrerNew.group_id = pddOrder.group_id;
            //GoodsItem goodsItem = new GoodsItem();
            //goodsItem.goods_id = good.goods_id;
            //goodsItem.sku_id = skuIdStr;
            //goodsItem.sku_id = good.sku_number;
            //pddOrerNew.goods = new List<GoodsItem>();
            //pddOrerNew.address_id = double.Parse(pddOrder.address_id);
            //pddOrerNew.anti_content = "";
            //pddOrerNew.attribute_fields = new Model.New.Attribute_fields();
            //pddOrerNew.is_app = "0";
            //pddOrerNew.page_id = "";
            //pddOrerNew.pay_app_id = 38;
            //pddOrerNew.source_type = 0;
            //pddOrerNew.version = 1;

            //Dictionary<string, string> dic_other = new Dictionary<string, string>();
            //dic_other.Add("AccessToken", pddToken.PDDAccessToken);

            //string ur1 = "http://apiv4.yangkeduo.com/order?pdduid=" + pddToken.pdd_user_id;


            //string Referer = "http://mobile.yangkeduo.com/search_result.html?search_key=" + this.source.Text + "&source=search&options=1&search_met_track=hot&refer_search_met_pos=0&refer_page_el_sn=615206&bui_search_id=" + pddOrder.group_id + "&refer_page_name=search&item_index=0&sp=0&is_back=1";
            //Referer = HttpUtility.UrlEncode(Referer);
            //// { "pay_app_id":9,"version":3,"attribute_fields":{ "paid_times":0,"forbid_contractcode":"1","forbid_pappay":"1"},"return_url":"http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=210313-556966544590499&prepay_type=","order_sn":"210313-556966544590499"}
            //string reslut1 = HttpHelper.HttpPost(ur1, JsonConvert.SerializeObject(pddOrder), null, "", Referer, "apiv4.yangkeduo.com", dic_other, address);

            if (this.puTongRadioButton.Checked)
            {
              await PuTongOrder(pddToken, pddOrder, daili);
            }

            if (this.duoduoRadioButton.Checked)
            {
                await DuoDuoOrder(pddGood, pddToken, pddOrder, daili);
            }

        }




        private void button10_Click(object sender, EventArgs e)
        {
            //string address = IPProxy.GetNewIp();
            //this.CurIP.Text = address;
            //"123.162.3.112:42877"
            //SetProxy(chromeBrowser, this.CurIP.Text);
        }

        async private void SetProxy(ChromiumWebBrowser cwb, string Address)
        {
            await Cef.UIThreadTaskFactory.StartNew(delegate
            {
                var rc = cwb.GetBrowser().GetHost().RequestContext;
                var v = new Dictionary<string, string>();
                v["mode"] = "fixed_servers";
                v["server"] = Address;
                string error;
                bool success = rc.SetPreference("proxy", v, out error);
                if (!string.IsNullOrWhiteSpace(error))
                {
                    MessageBox.Show(error, "Tip", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            });

        }

        private async void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            PddToken pddToken = this.dataGridView1.Rows[e.RowIndex].DataBoundItem as PddToken;
            if (pddToken == null)
            {
                return;
            }
            await context.GetCookieManager(null).DeleteCookiesAsync(pddurl, "PDDAccessToken");
            await context.GetCookieManager(null).DeleteCookiesAsync(pddurl, "pdd_user_id");

            var PDDAccessToken = new CefSharp.Cookie
            {
                Path = "/",
                Domain = "yangkeduo.com",
                Creation = DateTime.Today,
                Expires = DateTime.Today.AddDays(30),
                Name = "PDDAccessToken",
                Value = pddToken.PDDAccessToken
            };
            var pdd_user_id = new CefSharp.Cookie
            {
                Path = "/",
                Domain = "yangkeduo.com",
                Creation = DateTime.Today,
                Expires = DateTime.Today.AddDays(30),
                Name = "pdd_user_id",
                Value = pddToken.pdd_user_id
            };
            await context.GetCookieManager(null).SetCookieAsync(pddurl, pdd_user_id);
            await context.GetCookieManager(null).SetCookieAsync(pddurl, PDDAccessToken);
            string url1 = "http://mobile.yangkeduo.com/personal_profile.html";
            chromeBrowser.Load(url1);

            if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
            {
                var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

                if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    pddToken.status = "正常";
                }
                else if (pddUserInfo.Content.Contains("error_code"))
                {
                    pddToken.status = "过期";
                }
                else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    pddToken.status = "未知";
                }
            }
            else
            {
                pddToken.status = "未知";
            }
            pddTokenService.UpdateToken(pddToken, true);
            this.dataGridView1.Refresh();
        }

        private void button11_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = new AddToken().ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                var tokens = pddTokenService.GetAllToken();
                pddTokens.Clear();
                pddTokens = pddTokens.Concat(tokens).ToList();
                this.dataGridView1.DataSource = null;
                this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {

            if (this.dataGridView1.SelectedRows.Count < 0)
            {
                return;
            }

            PddToken pddToken = this.dataGridView1.CurrentRow.DataBoundItem as PddToken;
            if (pddToken == null)
            {
                return;
            }

            DialogResult dr = MessageBox.Show("您确定删除吗", "提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {

                bool reslut = DataBaseHelper.SqLiteDBCon.Delete(pddToken);
                if (reslut)
                {
                    var tokens = pddTokenService.GetAllToken();
                    pddTokens.Clear();
                    pddTokens = pddTokens.Concat(tokens).ToList();
                    this.dataGridView1.Rows.Remove(this.dataGridView1.CurrentRow);
                    //this.dataGridView1.DataSource = null;
                    //this.dataGridView1.DataSource = pddTokens;
                }
            }
        }

        private void button13_Click(object sender, EventArgs e)
        {
            string url = "http://yangkeduo.com/addresses.html?bind_phone_scene=personal_create_address&refer_page_name=personal";
            chromeBrowser.Load(url);
            //string ur1l ="http://yangkeduo.com/proxy/api/api/origenes/address?pdduid=7255740016769";
            //string ur1l ="http://apiv4.yangkeduo.com/address?pdduid=7255740016769";
        }


        private async Task<string> AddAddress(bool random, PddToken pddToken, string daili)
        {
            string address_id = "";
            PddAddress pddAddress = new PddAddress();
            PddAddressDBModel pddAddressDBModel = new PddAddressDBModel();
            while (true)
            {

                Random r = new Random();
                if (pddAddressDBModelList.Count() == 0)
                {
                    MessageBox.Show("地址库数据为空");
                    return address_id;
                }
                int index = r.Next(0, pddAddressDBModelList.Count());
                pddAddressDBModel = pddAddressDBModelList.ToList()[index];

                if (pddAddressDBModel != null)
                {

                    string[] addressArr = pddAddressDBModel.address.Split(' ');
                    if (addressArr.Length != 4)
                    {
                        continue;
                    }

                    var sheng = areaModelList.Where(x =>
                    {
                        return x.region_type == 1 && (x.region_name.Contains(addressArr[0]) || addressArr[0].Contains(x.region_name));
                    }).FirstOrDefault();
                    if (sheng == null)
                    {
                        continue;
                    }

                    var shi = areaModelList.Where(x =>
                    {
                        return x.region_type == 2 && sheng.region_id == x.parent_id && (x.region_name.Contains(addressArr[1]) || addressArr[1].Contains(x.region_name));
                    }).FirstOrDefault();

                    if (shi == null)
                    {
                        continue;
                    }

                    var xian = areaModelList.Where(x =>
                    {
                        return x.region_type == 3 && shi.region_id == x.parent_id && (x.region_name.Contains(addressArr[2]) || addressArr[2].Contains(x.region_name));
                    }).FirstOrDefault();

                    if (xian == null)
                    {
                        continue;
                    }
                    pddAddress.city_id = shi.region_id;
                    pddAddress.district_id = xian.region_id;
                    pddAddress.province_id = sheng.region_id;
                    pddAddress.name = this.NamePrefix.Text + pddAddressDBModel.name;
                    pddAddress.mobile = pddAddressDBModel.mobile;
                    pddAddress.address = addressArr[3];
                    pddAddress.is_default = "0";
                    break;
                }
                //else
                //{
                //    LogHelper.Logger.Error("地址有问题：" + pddAddressDBModel.address);

                //    MessageBox.Show("地址匹配失败");
                //    return address_id;
                //}
            }



            //Dictionary<string, string> dic_other = new Dictionary<string, string>();
            //dic_other.Add("AccessToken", pddToken.PDDAccessToken);
            //string ur1 = "http://apiv4.yangkeduo.com/address?pdduid=" + pddToken.pdd_user_id;
            //string reslut = HttpHelper.HttpPost(ur1, JsonConvert.SerializeObject(pddAddress), null, "", "http://apiv4.yangkeduo.com/address?pdduid=" + pddToken.pdd_user_id, "apiv4.yangkeduo.com", dic_other);

            var res = await PddApi.AddAddress(pddToken, pddAddress, daili);

            if (res.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(res.Content))
            {
                dynamic dyn = JsonConvert.DeserializeObject(res.Content);
                address_id = dyn.address_id;
                return address_id;
            }

            return address_id;

        }

        private async Task<JavascriptResponse> EvaluateJs(string js)
        {
            string script = @"(function() {  return  " + js + ";  })()";
            JavascriptResponse javascriptResponse = await chromeBrowser.EvaluateScriptAsync(script);
            return javascriptResponse;
        }



        private void button16_Click(object sender, EventArgs e)
        {
            string url = "http://yangkeduo.com/orders.html?type=1&comment_tab=1&combine_orders=1&refer_page_name=personal&refer_page_sn=10001";
            chromeBrowser.Load(url);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            string url = "http://yangkeduo.com/";
            chromeBrowser.Load(url);
        }

        private void button17_Click(object sender, EventArgs e)
        {

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                string text = File.ReadAllText(file);
                if (string.IsNullOrWhiteSpace(text))
                {
                    MessageBox.Show("数据为空");
                    return;
                }
                string[] striparr = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                var PddTokenList = pddTokenService.GetAllToken();
                foreach (var item in striparr)
                {
                    try
                    {
                        string[] sArray1 = item.Split(new char[4] { '-', '-', '-', '-' }, StringSplitOptions.RemoveEmptyEntries);
                        if (sArray1.Length != 3)
                        {
                            continue;
                        }
                        string qqOrPhone = sArray1[0];
                        string uid = sArray1[1];
                        string token = sArray1[2];
                        PddToken pddToken = new PddToken();
                        pddToken.pdd_user_id = uid;
                        pddToken.PDDAccessToken = token;
                        var pddT = PddTokenList.Where(x =>
                        {
                            return x.pdd_user_id == uid;
                        }).FirstOrDefault();
                        if (pddT != null)
                        {
                            pddToken.id = pddT.id;
                            pddTokenService.UpdateToken(pddToken);
                            //DataBaseHelper.SqLiteDBCon.Update<PddToken>(pddToken);
                        }
                        else
                        {
                            pddTokenService.InsertToken(pddToken);
                            //var reslut = DataBaseHelper.SqLiteDBCon.Insert<PddToken>(pddToken);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Logger.Error("导入小号失败", ex);
                    }

                }

                var tokens = pddTokenService.GetAllToken();
                pddTokens.Clear();
                pddTokens = pddTokens.Concat(tokens).ToList();

                this.dataGridView1.DataSource = new BindingList<PddToken>(pddTokens.Where(x => x.account_type != 1).ToList());
                comboBox1.DisplayMember = "Text";
                comboBox1.ValueMember = "Value";
                comboBox1.DataSource = items;
            }
        }

        /// <summary>
        /// Model对象转换为uri网址参数形式
        /// </summary>
        /// <param name="obj">Model对象</param>
        /// <param name="url">前部分网址</param>
        /// <returns></returns>
        public static string GetUriParam(object obj, string url = "")
        {
            PropertyInfo[] propertis = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            StringBuilder sb = new StringBuilder();
            sb.Append(url);
            //sb.Append("?");
            foreach (var p in propertis)
            {
                var v = p.GetValue(obj, null);
                if (v == null) v = "";

                sb.Append(p.Name);
                sb.Append("=");
                sb.Append(Uri.EscapeDataString(v.ToString()));//将字符串转换为它的转义表示形式，HttpUtility.UrlEncode是小写
                sb.Append("&");
            }
            sb.Remove(sb.Length - 1, 1);

            return sb.ToString();
        }

        /// <summary>
        /// 使DataGridView的列自适应宽度
        /// </summary>
        /// <param name="dgViewFiles"></param>
        private void AutoSizeColumn(DataGridView dgViewFiles)
        {
            int width = 0;
            //使列自使用宽度
            //对于DataGridView的每一个列都调整
            for (int i = 0; i < dgViewFiles.Columns.Count; i++)
            {
                //将每一列都调整为自动适应模式
                dgViewFiles.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                //记录整个DataGridView的宽度
                width += dgViewFiles.Columns[i].Width;
            }
            //判断调整后的宽度与原来设定的宽度的关系，如果是调整后的宽度大于原来设定的宽度，
            //则将DataGridView的列自动调整模式设置为显示的列即可，
            //如果是小于原来设定的宽度，将模式改为填充。
            if (width > dgViewFiles.Size.Width)
            {
                dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            }
            else
            {
                dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            //冻结某列 从左开始 0，1，2
            dgViewFiles.Columns[1].Frozen = true;
        }

        private async void button18_Click(object sender, EventArgs e)
        {
            await context.GetCookieManager(null).DeleteCookiesAsync();
            string url = "http://yangkeduo.com/";
            chromeBrowser.Load(url);
        }

        private void button19_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(this.goods_id.Text))
            {
                return;
            }
            string url = "http://km.chuangnuotong.com/xinhq.php?id=" + this.goods_id.Text + "&user=455120494";
            string str = HttpHelper.HttpGet_anzhou(url, "gb2312");
            if (string.IsNullOrWhiteSpace(str))
            {
                MessageBox.Show("获取失败");
                return;
            }
            PddGood pddGood = new PddGood();

            pddGood.sku = str;
            pddGood.good_id = this.goods_id.Text;
            pddGood.type = 5;
            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(this.goods_id.Text);
            if (pdd == null)
            {
                long reslut = DataBaseHelper.SqLiteDBCon.Insert<PddGood>(pddGood);
            }
            else
            {
                DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
            }

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (this.groupType.Text == "参团")
            //{
            //    //pddOrder.group_id = groupID.ToString();
            //    pddOrder.group_id = gIdList[1];
            //}
            //else if (this.groupType.Text == "开团")
            //{
            //    pddOrder.group_id = gIdList[1];
            //}
            //else if (this.groupType.Text == "单独购买")
            //{
            //    pddOrder.group_id = gIdList.FirstOrDefault();
            //}
        }

        /// <summary>
        /// 批量收藏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button8_Click(object sender, EventArgs e)
        {
            string goodId = this.goods_id.Text.Trim();
            foreach (DataGridViewRow item in this.dataGridView1.Rows)
            {

                PddToken pddToken = item.DataBoundItem as PddToken;

                var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

                if (string.IsNullOrWhiteSpace(pddUserInfo.Content))
                {
                    //MessageBox.Show("获取用户信息异常，小号可能过期了");
                    continue;
                }
                await PddApi.FavoriteGood(pddToken, goodId);

                //if (string.IsNullOrWhiteSpace(text))
                //{
                //    //MessageBox.Show("小号收藏失败");
                //}
            }
            MessageBox.Show("收藏成功");
        }

        /// <summary>
        /// 批量关注店铺
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e)
        {

        }

        private void button21_Click(object sender, EventArgs e)
        {
            //string url = "https://mobile.yangkeduo.com/proxy/api/order?pdduid=0";
        }

        private async void button5_Click_1(object sender, EventArgs e)
        {
            await AccountContext.GetCookieManager(null).FlushStoreAsync();

            List<CefSharp.Cookie> cookies2 = await AccountContext.GetCookieManager(null).VisitUrlCookiesAsync("http://mobile.yangkeduo.com", true);
            List<CefSharp.Cookie> cookies = await AccountContext.GetCookieManager(null).VisitAllCookiesAsync();
            if (cookies == null || cookies.Count == 0)
            {
                MessageBox.Show("请先登录账号");
                return;
            }

            CefSharp.Cookie PDDAccessTokenCookie = cookies.Where(x => { return x.Name == "PDDAccessToken"; }).FirstOrDefault();
            CefSharp.Cookie pdd_user_id_cookie = cookies.Where(x => { return x.Name == "pdd_user_id"; }).FirstOrDefault();
            if (PDDAccessTokenCookie == null || pdd_user_id_cookie == null)
            {
                MessageBox.Show("请先登录账号");
                return;
            }
            PddToken pddToken = pddTokenService.GetAllToken().Where(x => x.account_type == 1).FirstOrDefault();
            if (pddToken == null)
            {
                pddToken = new PddToken();
                pddToken.PDDAccessToken = PDDAccessTokenCookie.Value;
                pddToken.pdd_user_id = pdd_user_id_cookie.Value;
                pddToken.account_type = 1;
                long id = pddTokenService.InsertToken(pddToken, true);
                //long id = DataBaseHelper.SqLiteDBCon.Insert(pddToken);
                if (id > 0) { MessageBox.Show("设置成功"); }
            }
            else
            {
                pddToken.PDDAccessToken = PDDAccessTokenCookie.Value;
                pddToken.pdd_user_id = pdd_user_id_cookie.Value;
                pddToken.account_type = 1;
                bool reslut = pddTokenService.UpdateToken(pddToken, true);
                //bool reslut = DataBaseHelper.SqLiteDBCon.Update<PddToken>(pddToken);
                if (reslut) { MessageBox.Show("设置成功"); }

            }
            sku.SetCookie(AccountContext);
            AccountPddToken = pddToken;
        }

        //初始化浏览器并启动
        public void InitializeAccountChromium()
        {

            AccountContext = new RequestContext(new RequestContextSettings()
            {
                CachePath = AppDomain.CurrentDomain.BaseDirectory + "caches\\global2\\",
                PersistSessionCookies = true,
                PersistUserPreferences = true
            });

            AccountChromeBrowser = new ChromiumWebBrowser("http://yangkeduo.com/", AccountContext);

            AccountChromeBrowser.KeyboardHandler = new CEFKeyBoardHander();

            this.accountPanel.Controls.Add(AccountChromeBrowser);

            AccountChromeBrowser.Dock = DockStyle.Fill;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (AccountPddToken == null)
            {
                MessageBox.Show("请先登陆主账号");
                return;
            }

            if (this.pifaRadioButton.Checked)
            {
                string url = "https://pifa.pinduoduo.com/goods/detail/?gid=" + this.goods_id.Text.Trim();

                if (!sku.Visible)
                {
                    sku.Show();
                    sku.LoadUrl(url, 5000);
                }
                return;
            }


            PddGood pddGood = PddApi.GetGoodInfo2(this.goods_id.Text.Trim(), AccountPddToken);
            if (pddGood != null)
            {
                PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(this.goods_id.Text.Trim());

                SetGoodInfo(pdd);
                this.source.Text = pdd.SourceKeywords;

            }
        }

        private async void button18_Click_1(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("您确定退出登录吗", "提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                await AccountContext.GetCookieManager(null).DeleteCookiesAsync();
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //HakunaBrowser browser = new HakunaBrowser(this.chromeBrowser);
            //Wait wait = new Wait(this.chromeBrowser,500);
            //var ii= browser.FindElement("#pwd_unencrypt", 0);
            //ii.Click();
            //wait.UntilElementExist("#pwd_unencrypt");
            Browser.MouseLeftByHtmlElement("document.getElementById('pwd_unencrypt')", this.chromeBrowser, true);
            //Browser.MouseLeftByHtmlElement(ii.OuterHTML, this.chromeBrowser);

            //browser.FindElement(".text", 1).Click();
            //wait.UntilElementExist("#input_email");
            //browser.FindElement("#pwd_unencrypt").SendKeys("248789");
            //browser.FindElement(".-confirm").ToggleDisabled();

            //start process.
            //attach by friendly.

            Browser.Delay(300);
            SendKeys.SendWait("289698");
            //Auto.Ctrl_V("248789");
            //开始回复-复制粘贴
            //点击输入窗口


            //回车
            //Auto.Key_Enter();
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 1 /*绑定数据源中列的序号*/)
            {
                PddToken pddToken = this.dataGridView1.Rows[e.RowIndex].DataBoundItem as PddToken;
                if (string.IsNullOrWhiteSpace(pddToken.last_order_sn))
                {
                    return;
                }
                Order pddOrder = DataBaseHelper.SqLiteDBCon.Get<Order>(pddToken.last_order_sn);

                if (pddOrder == null)
                {
                    return;
                }

                DateTime time = Convert.ToDateTime(pddOrder.buyTime);
                DateTime now = DateTime.Now;
                DateTime today = new DateTime(now.Year, now.Month, now.Day);//当天的零时零分

                if (time < today)
                {
                    e.Value = "";
                }

            }

        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            //调用系统默认的浏览器
            System.Diagnostics.Process.Start("http://www.pdd88.top/home");
        }

        private void button14_Click(object sender, EventArgs e)
        {
            //string url = "http://mobile.pinduoduo.com/chat_detail.html?mall_id=571065254&goods_id=235080585096&cat_id_1=17285&page_from=35&is_full_reduction=false&is_full_return=false&refer_page_name=goods_detail&refer_page_id=10014_1620905888814_q2glidocqv&refer_page_sn=10014";
            //  string url = "http://yangkeduo.com/chat_detail.html?order_sn=210508-478868941672933&goods_name=%E6%B5%B4%E5%AE%A4%E6%B6%88%E6%AF%92%E6%B8%85%E6%B4%81%E5%89%82%E7%93%B7%E7%A0%96%E7%8E%BB%E7%92%83%E6%B5%B4%E7%BC%B8%E6%B8%85%E6%B4%97%E7%A5%9E%E5%99%A8%E5%8D%AB%E7%94%9F%E9%97%B4%E6%B0%B4%E5%9E%A2%E6%B8%85%E9%99%A4%E5%BC%BA%E5%8A%9B%E5%8E%BB%E6%B1%A1%E9%99%A4%E5%9E%A2&thumb_url=https%3A%2F%2Fimg.pddpic.com%2Fmms-material-img%2F2020-08-13%2Fc706f1e8-4ebb-4498-8bf9-ef72f5514486.jpeg.a.jpeg&goods_thumb_url=https%3A%2F%2Fimg.pddpic.com%2Fmms-material-img%2F2020-08-13%2Fc706f1e8-4ebb-4498-8bf9-ef72f5514486.jpeg.a.jpeg&order_time=1620467310&status_desc=%E4%BA%A4%E6%98%93%E5%B7%B2%E5%8F%96%E6%B6%88&mall_id=620613496&from=order&refer_page_name=order_detail&refer_page_id=10038_1620891334296_o20ww1wlbo&refer_page_sn=10038";
        }

        private BrowserFrom sku;

        private void button7_Click_1(object sender, EventArgs e)
        {
            string json = "{\"gateway_url\":\"https://mapi.alipay.com/gateway.do\",\"query\":{\"_input_charset\":\"utf-8\",\"goods_type\":\"1\",\"it_b_pay\":\"2021-05-21 19:04\",\"notify_url\":\"https://paynotify.pinduoduo.com/notify/9\",\"out_trade_no\":\"XP2521052019201449526067001197\",\"partner\":\"2088911201740274\",\"payment_type\":\"1\",\"return_url\":\"https://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=PO-210520-190620703423806&prepay_type=combine\",\"seller_id\":\"pddzhifubao@yiran.com\",\"service\":\"alipay.wap.create.direct.pay.by.user\",\"sign\":\"IaPl3JWsvL9xkq0gkKd30insfB+4bNxjSns/Vb4a0ylBWnsJzVSH+DZdyylwxBznyxOOTb4Wm6O91aY/0z64ocvraPju7LYQ4JkKBob4/GKPbyQ6w2EM7ECzqZuFytYa4gpcRbNv/jIffV6OpdzdmO1q813POpY9ZrWKGPLDVvQ=\",\"sign_type\":\"RSA\",\"subject\":\"商户单号XP2521052019201449526067001197\",\"total_fee\":\"30.42\"},\"server_time\":1621508695,\"status\":10000}";
            var jo = JObject.Parse(json);
            var query = jo["query"];
            var gateway_url = jo["gateway_url"];

            StringBuilder stringBuilder = new StringBuilder();
            foreach (JToken grandChild in query)
            {
                stringBuilder.Append("&");
                var p = grandChild as JProperty;
                string s = p.Name + ":" + p.Value;
                stringBuilder.Append(p.Name);
                stringBuilder.Append("=");
                stringBuilder.Append(Uri.EscapeDataString(p.Value.ToString()));
                stringBuilder.Append("&");
            }
            stringBuilder.Remove(stringBuilder.Length - 1, 1);
            string url = gateway_url + "?" + stringBuilder.ToString();
            Console.WriteLine(stringBuilder);

            //String ttt=  FackUtil.GetAnti(chromeBrowser,"");
            // string html = File.ReadAllText(@"F:\谷歌下载\anti_content-main\src\test.html");
            //  PaserOrderHtml(html);
            //string url = "https://pifa.pinduoduo.com/goods/detail/?gid=" + this.goods_id.Text.Trim();

            //if (!sku.Visible)
            //{
            //    sku.LoadUrl(url, 5000);
            //    sku.Show();
            //}

            //      var str = sku.myRequestHandler.ToString();
            ////提取某一个url拦截的数据
            //var fd = sku.myRequestHandler.Filters.FirstOrDefault(f => f.Name == "queryGoodsDetail");
            //var HasData = fd?.HasData;
            //var data = fd?.Filter?.DataStr;

            //var response = await PddApi.GetGoodInfo(this.goods_id.Text.Trim(), AccountPddToken);
            //var res = await PddPiFaApi.QueryGoodsQaList(this.goods_id.Text.Trim(), AccountPddToken);
        }
        ClientWebSocket _webSocket;

        private async void button10_Click_1(object sender, EventArgs e)
        {
            _webSocket = new ClientWebSocket();
            //_webSocket.Options = new ClientWebSocketOptions();

            //建立连接
            //var url = "wss://ws.pinduoduo.com/?role=user&client=web&enable_bubble=true&access_token=3H7I7A4UR2CT7MKKAWKOFJ7VCSJ65PO3OO4T6V4KDOPNWF55K3WA1101f2a";
            var url = "wss://ws.pinduoduo.com/?role=user&client=web&enable_bubble=true&access_token=74VGGNNSVCSOBUPSCIPZ6PIW5O3G5GQTQ4WHY3V2FL6TASJQS73A1112973";

            await _webSocket.ConnectAsync(new Uri(url), CancellationToken.None);

            if (_webSocket.State != WebSocketState.Open)
            {
                return;
            }

            byte[] bufSize = new byte[1 * 1024];
            ArraySegment<byte> buf = new ArraySegment<byte>(bufSize);
            WebSocketReceiveResult r = await _webSocket.ReceiveAsync(buf, CancellationToken.None);
            string str = System.Text.Encoding.Default.GetString(bufSize);

            //{"auth":{"result":"ok"},"request_id":"1621323925","response":"auth","result":"ok","server_time":1621323925704,"status":1,"uid":"1363852664863"}
            var jo = JObject.Parse(str);
            var result = jo["auth"]["result"].ToString();

            if (result != "ok")
            {
                return;
            }
            // 9082252024311----EEJN44M2JB3SYNHJDPIQA4LUDEPX4UGZYN3DAJXVUGZV6PTVTT5A111f777
            var upload_sign = await PddApi.Signature(new PddToken() { pdd_user_id = "9082252024311", PDDAccessToken = "EEJN44M2JB3SYNHJDPIQA4LUDEPX4UGZYN3DAJXVUGZV6PTVTT5A111f777" }, null, "pdd_chat_image");

            // string json = "{\"cmd\":\"send_message\",\"message\":{\"from\":{\"role\":\"user\",\"uid\":\"1363852664863\"},\"to\":{\"role\":\"mall\",\"uid\":\"627671\"},\"content\":\"https://t00img.yangkeduo.com/chat/chat_user_upload/2021-05-18/9982935159702f1bed3ec1590f8c3fd9.jpeg\",\"type\":1},\"version\":2,\"refer_page_name\":\"mall\",\"login_app_id\":\"\",\"anti_content\":\"0aoAfxnUOy1gYgdC4ApkP7AAtUCHSCf1D_LrLXRHY1Tj2tFHD7_Tsf2yHMcDGfUu-kqj_vnIMoT7r06rUFYtVkONtPoqPsqhcRXmBEk0T0C0N4gjaCrVcc14eKWPQZiBiOg6gqI1OPtCUi-MZRns-rnFgahVDJyzM4wRKa7vW6_m7PNqk_onyqnsZtKOw8I8fs3FZFL7c7xuvI1h6WsO--RpTe-8zkEu46tFvemRODkus4tvfwwozmZd5o7D71d1dwmOSMRpxvGp2J5VgZgQAkLy6nua04GzGYFt6g8fGJKIn_yYQMhCnLy2pS8ihAcEQx8cYmrst6X9j97xMUpO2Jjomb7r9a-J1-GTCib4Pm2oogt396j4_Ec4mG9aapHoG-e39X9MHnmz-BXBm74bJo_a-ngA2x6M6Q-gUtMsPnLm2U8F9FDDHfNAG-gJ0XSE_7dZub-dMG6Hb6v6ecb3Q7tlVyeBnMSFp7iXQDuQkOWsstXa7_EvEb69bh3vMWJDMpxWOi_jdfEDYzrY6hzJuxrU694eZlDVHZyXzGzldNb-W8wo0LmIG1pP5Fz8-ZKZO6s2P8EwgW3DlMKN7Ixm_9s3KXGLk7roO2yu7W32_qpqO8ig-52SCDC4ApySrQH64hHMoY-oil5jehpwgbEWNDIRTf93NA_\",\"user_agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\",\"request_id\":8}";
            string json = "{\"cmd\":\"send_message\",\"message\":{\"from\":{\"role\":\"user\",\"uid\":\"1363852664863\"},\"to\":{\"role\":\"mall\",\"uid\":\"627671\"},\"content\":\"https://t00img.yangkeduo.com/chat/chat_user_upload/2021-05-18/9982935159702f1bed3ec1590f8c3fd9.jpeg\",\"type\":1},\"version\":2,\"refer_page_name\":\"mall\",\"login_app_id\":\"\",\"anti_content\":\"0aoAfxnUOy1gYgdC4ApkP7AAtUCHSCf1D_LrLXRHY1Tj2tFHD7_Tsf2yHMcDGfUu-kqj_vnIMoT7r06rUFYtVkONtPoqPsqhcRXmBEk0T0C0N4gjaCrVcc14eKWPQZiBiOg6gqI1OPtCUi-MZRns-rnFgahVDJyzM4wRKa7vW6_m7PNqk_onyqnsZtKOw8I8fs3FZFL7c7xuvI1h6WsO--RpTe-8zkEu46tFvemRODkus4tvfwwozmZd5o7D71d1dwmOSMRpxvGp2J5VgZgQAkLy6nua04GzGYFt6g8fGJKIn_yYQMhCnLy2pS8ihAcEQx8cYmrst6X9j97xMUpO2Jjomb7r9a-J1-GTCib4Pm2oogt396j4_Ec4mG9aapHoG-e39X9MHnmz-BXBm74bJo_a-ngA2x6M6Q-gUtMsPnLm2U8F9FDDHfNAG-gJ0XSE_7dZub-dMG6Hb6v6ecb3Q7tlVyeBnMSFp7iXQDuQkOWsstXa7_EvEb69bh3vMWJDMpxWOi_jdfEDYzrY6hzJuxrU694eZlDVHZyXzGzldNb-W8wo0LmIG1pP5Fz8-ZKZO6s2P8EwgW3DlMKN7Ixm_9s3KXGLk7roO2yu7W32_qpqO8ig-52SCDC4ApySrQH64hHMoY-oil5jehpwgbEWNDIRTf93NA_\",\"user_agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\",\"request_id\":8}";
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(json);
            await _webSocket.SendAsync(new ArraySegment<byte>(byteArray), WebSocketMessageType.Binary, true, CancellationToken.None);
            await Task.Run(ReceiveData);
            //var bsend = new byte[1024];
            //string json = "{\"cmd\":\"send_message\",\"message\":{\"from\":{\"role\":\"user\",\"uid\":\"1363852664863\"},\"to\":{\"role\":\"mall\",\"uid\":\"627671\"},\"content\":\"您好，啥时候到啊，等不及了\",\"type\":0},\"version\":2,\"refer_page_name\":\"mall\",\"login_app_id\":\"\",\"anti_content\":\"0aoAfxnUOy1gYgdC4ApkP7AAtUCHSCf1D_LrLXRHY1Tj2tFHD7_Tsf2yHMcDGfUu-kqj_vnIMoT7r06rUFYtVkONtPoqPsqhcRXmBEk0T0C0N4gjaCrVcc14eKWPQZiBiOg6gqI1OPtCUi-MZRns-rnFgahVDJyzM4wRKa7vW6_m7PNqk_onyqnsZtKOw8I8fs3FZFL7c7xuvI1h6WsO--RpTe-8zkEu46tFvemRODkus4tvfwwozmZd5o7D71d1dwmOSMRpxvGp2J5VgZgQAkLy6nua04GzGYFt6g8fGJKIn_yYQMhCnLy2pS8ihAcEQx8cYmrst6X9j97xMUpO2Jjomb7r9a-J1-GTCib4Pm2oogt396j4_Ec4mG9aapHoG-e39X9MHnmz-BXBm74bJo_a-ngA2x6M6Q-gUtMsPnLm2U8F9FDDHfNAG-gJ0XSE_7dZub-dMG6Hb6v6ecb3Q7tlVyeBnMSFp7iXQDuQkOWsstXa7_EvEb69bh3vMWJDMpxWOi_jdfEDYzrY6hzJuxrU694eZlDVHZyXzGzldNb-W8wo0LmIG1pP5Fz8-ZKZO6s2P8EwgW3DlMKN7Ixm_9s3KXGLk7roO2yu7W32_qpqO8ig-52SCDC4ApySrQH64hHMoY-oil5jehpwgbEWNDIRTf93NA_\",\"user_agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\",\"request_id\":8}";
            //await _webSocket.SendAsync(new ArraySegment<byte>(bsend), WebSocketMessageType.Binary, true, CancellationToken.None); //发送数据

            //while (true)
            //{
            //    var result = new byte[1024];

            //    await _webSocket.ReceiveAsync(new ArraySegment<byte>(result), CancellationToken.None);//接受数据
            //    //new string(result);
            //    string str = System.Text.Encoding.Default.GetString(result);
            //    //var lastbyte = ByteCut(result, 0x00);

            //    //var str = Encoding.UTF8.GetString(lastbyte, 0, lastbyte.Length);
            //    await Task.Delay(100);
            //}


        }

        async void ReceiveData()
        {
            while (true)
            {
                byte[] bufSize = new byte[4 * 1024];
                ArraySegment<byte> buf = new ArraySegment<byte>(bufSize);
                WebSocketReceiveResult r = await _webSocket.ReceiveAsync(buf, CancellationToken.None);
                string str = System.Text.Encoding.Default.GetString(bufSize);
                //{"auth":{"result":"ok"},"request_id":"1621323925","response":"auth","result":"ok","server_time":1621323925704,"status":1,"uid":"1363852664863"}
                //var jo  = JObject.Parse(str);
                //var result = jo["auth"]["result"].ToString();
                //if (result == "ok") 
                //{

                //    string json = "{\"cmd\":\"send_message\",\"message\":{\"from\":{\"role\":\"user\",\"uid\":\"1363852664863\"},\"to\":{\"role\":\"mall\",\"uid\":\"627671\"},\"content\":\"您好，啥时候到啊，等不及了\",\"type\":0},\"version\":2,\"refer_page_name\":\"mall\",\"login_app_id\":\"\",\"anti_content\":\"0aoAfxnUOy1gYgdC4ApkP7AAtUCHSCf1D_LrLXRHY1Tj2tFHD7_Tsf2yHMcDGfUu-kqj_vnIMoT7r06rUFYtVkONtPoqPsqhcRXmBEk0T0C0N4gjaCrVcc14eKWPQZiBiOg6gqI1OPtCUi-MZRns-rnFgahVDJyzM4wRKa7vW6_m7PNqk_onyqnsZtKOw8I8fs3FZFL7c7xuvI1h6WsO--RpTe-8zkEu46tFvemRODkus4tvfwwozmZd5o7D71d1dwmOSMRpxvGp2J5VgZgQAkLy6nua04GzGYFt6g8fGJKIn_yYQMhCnLy2pS8ihAcEQx8cYmrst6X9j97xMUpO2Jjomb7r9a-J1-GTCib4Pm2oogt396j4_Ec4mG9aapHoG-e39X9MHnmz-BXBm74bJo_a-ngA2x6M6Q-gUtMsPnLm2U8F9FDDHfNAG-gJ0XSE_7dZub-dMG6Hb6v6ecb3Q7tlVyeBnMSFp7iXQDuQkOWsstXa7_EvEb69bh3vMWJDMpxWOi_jdfEDYzrY6hzJuxrU694eZlDVHZyXzGzldNb-W8wo0LmIG1pP5Fz8-ZKZO6s2P8EwgW3DlMKN7Ixm_9s3KXGLk7roO2yu7W32_qpqO8ig-52SCDC4ApySrQH64hHMoY-oil5jehpwgbEWNDIRTf93NA_\",\"user_agent\":\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\",\"request_id\":8}";
                //     byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(json);
                //    await _webSocket.SendAsync(new ArraySegment<byte>(byteArray), WebSocketMessageType.Binary, true, CancellationToken.None);
                //}

            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var tab = this.tabControl1.SelectedTab;
            if (tab.Text == "订单管理")
            {
                this.orderControl1.LoadData();
            }

            //var tab = sender as System.Windows.Forms.TabControl;
        }

        private void orderControl1_Load(object sender, EventArgs e)
        {

        }
    }
}
